<script>
	import Vue from 'vue'
	import store from './store/index.js'
	import Config from './utils/config.js'
	import updateCustomBarInfo from './uni_modules/tuniao-ui/libs/function/updateCustomBarInfo.js'
	import common_mixin from '@/libs/mixin/common_mixin.js'
  import {
    getStorageSync,
    setStorageSync, toast
  } from "./utils/utils";

	// #ifdef APP-PLUS
	import appUpdate from '@/components/appUpdate/appUpdate.js'
	// #endif

	export default {
		mixins: [common_mixin],
		onLaunch: function(options) {
			console.log("options:",options)
			if(options.query.tfid){
				uni.setStorageSync('tfid', options.query.tfid)
			}
			if(options.query.invite_code){
				uni.setStorageSync('invite_code', options.query.invite_code)
			}
			if(options.query.middleman_id){
				uni.setStorageSync('middleman_id', options.query.middleman_id)
			}
			if(options.query.agent_id){
				uni.setStorageSync('agent_id', options.query.agent_id)
			}

			this.toUpdateCustomBarInfo()
			this.checkSystemPlatform()
			this.checkAppUpdate()
			this.checkMpUpdate();
			this.fetchAppInfo();
			if(Config.isWeChat){
				this.wxLoginWay();
			} else{
				this.h5Login();
			}
		},
		onShow: function() {},
		methods: {
			async h5Login(){
				let username = getStorageSync('h5_username');
				if(!username){
					username = Config.getRandomString(16);
				}
				const res = await this.$api.h5Login({
					username:username,
					invite_code: getStorageSync('invite_code') || 0,
					tfid: getStorageSync('tfid') || 0,
					middleman_id: getStorageSync('middleman_id') || 0,
					agent_id: getStorageSync('agent_id') || 0
				});
				const userinfo = res.userinfo;
				this.loginSuccess(userinfo);
			},
			//微信登录方式判断
			async wxLoginWay() {
				let username = getStorageSync('h5_username');
				if (username) {
					//用已有缓存账号登陆
					let params = {
						invite_code: getStorageSync('invite_code') || 0,
						tfid: getStorageSync('tfid') || 0,
						middleman_id: getStorageSync('middleman_id') || 0,
						agent_id: getStorageSync('agent_id') || 0,
						username: username,
						code: '',
					};
					// 如果存在用户名，直接使用用户名和code进行登录
					await this.wxLogin(params);
				} else {
					await this.wxGetCodeLogin();
				}
			},
			//获取code登录
			async wxGetCodeLogin() {
				// 否则获取code再进行登录
				uni.login({
					provider: 'weixin', // 使用微信登录
					success: async function(loginRes) {
						console.log("wx:" + JSON.stringify(loginRes));
						let code = loginRes.code;
						let params = {
							invite_code: getStorageSync('invite_code') || 0,
							tfid: getStorageSync('tfid') || 0,
							middleman_id: getStorageSync('middleman_id') || 0,
							agent_id: getStorageSync('agent_id') || 0,
							username: '',
							code: code,
						};
						await this.wxLogin(params);
					}.bind(this)
				});
			},
			//微信登录动作
			async wxLogin(params) {
				const res = await this.$api.wxLogin(params);
				if(res){
					const userinfo = res.userinfo;
					this.loginSuccess(userinfo);
				}else{
					if(!params.code){ //账号登陆失败，获取code再登录一次
						await this.wxGetCodeLogin();
					}
				}
			},
			loginSuccess(userinfo){
				setStorageSync("token", userinfo.token);
				setStorageSync("h5_username", userinfo.username);
				//判断用户的会员到期没有，到期的话就把plus_type改为0
				let nowtime = new Date().getTime()
				if (userinfo.plus_expire_time * 1000 < nowtime && userinfo.plus_type == 1) {
					userinfo.plus_type = 0;
					console.log("用户会员已过期，改为普通用户");
					this.$api.updateUserPlus({});
				}

				store.commit('$tStore', {
					name: 'vuex_user',
					value: userinfo
				});
				if (!userinfo.mobile) {
				  	console.log('需要绑定手机号');
					uni.navigateTo({
					    url: '/pages_sub/invite/bindphone'
					});
				}
			},
			async fetchAppInfo() {
				let res = await this.$api.getAppInfo();
				this.$t.vuex('appInfo', res.appInfo ? res.appInfo : {})
				this.$t.vuex('adConfig', res.adConfig ? res.adConfig : {})
			},
			checkSystemPlatform() {
				uni.getSystemInfo({
					success: function(e) {
						// #ifndef H5
						// 获取手机系统版本
						const system = e.system.toLowerCase()
						const platform = e.platform.toLowerCase()
						// 判断是否为ios设备
						if (platform.indexOf('ios') != -1 && (system.indexOf('ios') != -1 || system.indexOf(
								'macos') != -1)) {
							Vue.prototype.SystemPlatform = 'apple'
						} else if (platform.indexOf('android') != -1 && (system.indexOf('android') != -1)) {
							Vue.prototype.SystemPlatform = 'android'
						} else {
							Vue.prototype.SystemPlatform = 'devtools'
						}
						// #endif
					}
				})
			},
			checkAppUpdate() {
				// #ifdef APP-PLUS
				let systemInfo = uni.getSystemInfoSync()
				const data = {
					appid: systemInfo.appId,
					version: systemInfo.appVersion
				}
				console.log(data)
				//把appid和版本发送请求服务器，看服务器上是否有更新
				this.$api.checkVersion(data).then(res => {
					console.log(res)
					if (res.code == 0) {
						//如果返回0则表示有更新
						appUpdate(res)
					}
				})
				// #endif
			},
			toUpdateCustomBarInfo() {
				// 获取设备的状态栏信息和自定义顶栏信息
				// store.dispatch('updateCustomBarInfo')
				updateCustomBarInfo().then((res) => {
					store.commit('$tStore', {
						name: 'vuex_status_bar_height',
						value: res.statusBarHeight
					})
					store.commit('$tStore', {
						name: 'vuex_custom_bar_height',
						value: res.customBarHeight
					})
				})
			},
			checkMpUpdate() {
				// #ifdef MP-WEIXIN
				//更新检测
				if (wx.canIUse('getUpdateManager')) {
					const updateManager = wx.getUpdateManager();
					updateManager && updateManager.onCheckForUpdate((res) => {
						if (res.hasUpdate) {
							updateManager.onUpdateReady(() => {
								uni.showModal({
									title: '更新提示',
									content: '新版本已经准备就绪，是否需要重新启动应用？',
									success: (res) => {
										if (res.confirm) {
											uni.clearStorageSync() // 更新完成后刷新storage的数据
											updateManager.applyUpdate()
										}
									}
								})
							})

							updateManager.onUpdateFailed(() => {
								uni.showModal({
									title: '已有新版本上线',
									content: '小程序自动更新失败，请删除该小程序后重新搜索打开哟~~~',
									showCancel: false
								})
							})
						} else {
							//没有更新
						}
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '当前微信版本过低，无法使用该功能，请更新到最新的微信后再重试。',
						showCancel: false
					})
				}
				// #endif
			}
		}
	}
</script>
<style lang="scss">
	@import "@/uni_modules/uview-ui/index.scss";
	@import '@/uni_modules/tuniao-ui/index.scss';
	@import '@/uni_modules/tuniao-ui/iconfont.css';
	@import '@/static/css/custom.scss';
</style>
